/**
 * Copyright (C) 2008 Happy Fish / YuQing
 * <p>
 * FastDFS Java Client may be copied only under the terms of the GNU Lesser
 * General Public License (LGPL).
 * Please visit the FastDFS Home Page https://github.com/happyfish100/fastdfs for more detail.
 */

package cc.siyecao.fastdfs.server;

import cc.siyecao.fastdfs.command.FdfsCommand;
import cc.siyecao.fastdfs.extception.FastDfsException;
import cc.siyecao.fastdfs.pool.FdfsConnection;
import cc.siyecao.fastdfs.pool.FdfsConnectionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.InetSocketAddress;

/**
 * Storage Server Info
 *
 * @author Happy Fish / YuQing
 * @version Version 1.11
 */
@Component
public class StorageServer {

    @Autowired
    private FdfsConnectionManager fdfsConnectionManager;

    public FdfsConnection getConnection(InetSocketAddress inetSockAddr) throws FastDfsException, IOException {
        return fdfsConnectionManager.getConnection( inetSockAddr );
    }

    public <T> T excuteCmd(InetSocketAddress inetSockAddr, FdfsCommand<T> fdfsCommand) {
        FdfsConnection fdfsConnection = null;
        try {
            fdfsConnection = getConnection( inetSockAddr );
            return fdfsCommand.execute( fdfsConnection );
        } catch (Exception exception) {
            throw new FastDfsException( "exception occured while sending cmd", exception );
        } finally {
            if (fdfsConnection != null) {
                try {
                    fdfsConnection.release();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
